"""
设计一个工具来帮助社团成员组织和管理活动。该工具允许用户创建和查看活动，更新已有活动信息，保存活动记录，并以格式化的方式展示所有活动信息。
1.用户可以单独或批量输入活动信息，创建新的活动记录。
2.支持更新已有活动信息、删除特定活动以及按条件筛选活动。
3.所有活动记录能够持久化存储，并支持数据导出。
4.支持活动统计与分析，便于用户了解活动情况。
"""

import os

# 成员A负责的功能（党妍妍）
def input_activity():
     activities = []
     while True:
         single_activity = {}
         # 输入活动名称
         name = input("请输入活动名称（不能为空）：")
         while not name:
             name = input("活动名称不能为空，请重新输入：")
         single_activity["活动名称"] = name
         # 输入日期
         date = input("请输入日期（格式为YYYY - MM - DD）：")
         try:
             # 检查日期格式是否正确
             if len(date)!= 10 or date[4]!= '-' or date[7]!= '-':
                 raise ValueError
             parts = date.split('-')
             int(parts[0])
             int(parts[1])
             int(parts[2])
             single_activity["日期"] = date
         except ValueError:
             print("日期格式错误，请重新输入")
             continue
         # 输入时间
         time = input("请输入时间（格式为HH:MM）：")
         try:
             if len(time)!= 5 or time[2]!= ':':
                 raise ValueError
             parts = time.split(':')
             int(parts[0])
             int(parts[1])
             single_activity["时间"] = time
         except ValueError:
             print("时间格式错误，请重新输入")
             continue
         # 输入地点
         single_activity["地点"] = input("请输入地点：")
         # 输入描述
         single_activity["描述"] = input("请输入活动描述：")
         activities.append(single_activity)
         choice = input("是否继续输入活动（y/n）？")
         if choice.lower()!= 'y':
             break
     return activities

# 成员B负责的功能（郭文杰）
def update_delete_activities(new_activities, old_activities):
     all_activities = old_activities.copy()
     for new_activity in new_activities:
         name = new_activity["活动名称"]
         found = False
         for i, old_activity in enumerate(all_activities):
             if old_activity["活动名称"] == name:
                 found = True
                 choice = input(f"活动 {name} 已存在，选择：[u]更新/[s]跳过/[d]删除：")
                 if choice.lower() == 'u':
                     all_activities[i] = new_activity
                 elif choice.lower() == 'd':
                     confirm = input(f"确定要删除活动 {name} 吗？(y/n)")
                     if confirm.lower() == 'y':
                         all_activities.pop(i)
                 break
         if not found:
             all_activities.append(new_activity)
     return all_activities

# 成员C负责的功能（莫炯森）
def read_activities_from_file():
     if not os.path.exists('activities.txt'):
         return []
     activities = []
     with open('activities.txt', 'r', encoding="UTF-8") as f:
         lines = f.readlines()
         i = 0
         while i < len(lines):
             activity = {}
             activity["活动名称"] = lines[i].strip()
             activity["日期"] = lines[i + 1].strip()
             activity["时间"] = lines[i + 2].strip()
             activity["地点"] = lines[i + 3].strip()
             activity["描述"] = lines[i + 4].strip()
             activities.append(activity)
             i += 5
     return activities
def save_activities_to_file(activities):
     with open('activities.txt', 'w', encoding="UTF-8") as f:
         for activity in activities:
             f.write(activity["活动名称"] + '\n')
             f.write(activity["日期"] + '\n')
             f.write(activity["时间"] + '\n')
             f.write(activity["地点"] + '\n')
             f.write(activity["描述"] + '\n')
def print_activities(activities):
     for activity in activities:
         print("活动名称：", activity["活动名称"])
         print("日期：", activity["日期"])
         print("时间：", activity["时间"])
         print("地点：", activity["地点"])
         print("描述：", activity["描述"])
         print()
def filter_activities(activities, filter_type, value):
     filtered_activities = []
     if filter_type == "日期":
         for activity in activities:
             if activity["日期"] == value:
                 filtered_activities.append(activity)
     elif filter_type == "地点":
         for activity in activities:
             if activity["地点"] == value:
                 filtered_activities.append(activity)
     return filtered_activities

# 成员D负责的功能（萧海华）
def main():
     new_activities = input_activity()
     old_activities = read_activities_from_file()
     updated_activities = update_delete_activities(new_activities, old_activities)
     save_activities_to_file(updated_activities)
     print("所有活动信息：")
     print_activities(updated_activities)
     filter_type = input("按[日期/地点]筛选活动：")
     value = input(f"请输入要筛选的{filter_type}：")
     filtered = filter_activities(updated_activities, filter_type, value)
     print(f"筛选后的{filter_type}为{value}的活动：")
     print_activities(filtered)
     # 统计活动总数
     total_count = len(updated_activities)
     print("活动总数：", total_count)
     # 统计每月活动数量
     monthly_count = {}
     for activity in updated_activities:
         month = activity["日期"][5:7]
         if month not in monthly_count:
             monthly_count[month] = 1
         else:
             monthly_count[month] += 1
     print("每月活动数量：", monthly_count)
     # 找出活动最频繁的地点
     location_count = {}
     for activity in updated_activities:
         location = activity["地点"]
         if location not in location_count:
             location_count[location] = 1
         else:
             location_count[location] += 1
     max_count = 0
     most_frequent_location = ""
     for location, count in location_count.items():
         if count > max_count:
             max_count = count
             most_frequent_location = location
     print("活动最频繁的地点：", most_frequent_location)
if __name__ == '__main__':
     main()
